const app = getApp();

interface paramsData {
  SurveyId: string; // 指向调查表
  QuestionId: string; // 指向问题表
  OptionId?: string; //指向选项表，如果问题是文本输入则为空
  RespondentId: string; //回答者ID
  ResponseText?: string; // 如果问题是文本输入，则保存文本回答
  ResponseDateTime: string;
}

Page({
  data: {
    safeDistance: {}, // 用于存储安全区域信息
    questionObj: {}, //问卷的数据对象
  },

  onLoad: function () {
    // 从全局变量中获取安全距离信息
    const safeDistance = app.globalData.safeDistance;

    this.setData({
      safeDistance: safeDistance,
    });

    this.loadData();
  },

  /**
   * 提交表单
   * @param e
   */
  submitForm(e: any) {
    const formData = e.detail.value;
    console.log('提交的表单数据：', formData);

    for (const key in formData) {
      // 遍历表单项，检查是否有选项为空
      const item = formData[key];
      if (!item) {
        wx.showToast({
          title: '请填写完所有问题再重新提交!!!',
          icon: 'none',
        });
        return;
      }
    }

    this.save(formData);
  },

  /**
   * 将表单数据提交给后台
   */
  save(formData: any) {
    const responseData = [];
    const SurveyId = this.data.questionObj.id;
    const RespondentId = 'userAJiang9';

    for (const key in formData) {
      const data: paramsData = {
        SurveyId,
        QuestionId: '1',
        OptionId: formData[key],
        RespondentId,
        ResponseDateTime: new Date().toISOString(),
      };

      responseData.push(data);
    }

    console.log(responseData);

    wx.request({
      method: 'POST',
      url: `http://wwww.localhost:4000/api/survey/save/${SurveyId}/${RespondentId}`,
      data: {
        responses: responseData,
      },
      success: (res) => {
        console.log(res);
      },
      fail: (error) => {
        console.log(error);
      },
    });
  },

  /**
   * 根据id获取问卷数据
   */
  loadData() {
    wx.request({
      method: 'POST',
      url: 'http://wwww.localhost:4000/api/survey/findSurveyBySurveyId',
      data: {
        surveyId: '1',
      },
      success: (res) => {
        this.setData({
          questionObj: res.data as never,
        });
        console.log(this.data.questionObj);
      },
    });
  },
});
